import logging
import logging.config
import time

import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from config.setting import setting_config
from core.logging_config import LOGGING_CONFIG

# 初始化日志
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("app")

app = FastAPI(
    title=setting_config.app.name,
    description=setting_config.app.description,
    version=setting_config.app.version,
    debug=setting_config.app.debug,
    docs_url="/docs" if setting_config.app.debug else None,
    redoc_url="/redoc" if setting_config.app.debug else None,
)


# 请求耗时 & 异常统一记录（ERROR 会进入 error.log，含堆栈）
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start = time.time()
    try:
        response = await call_next(request)
        cost = (time.time() - start) * 1000
        logger.info("%s %s -> %s (%.2f ms)", request.method, request.url.path, response.status_code, cost)
        return response
    except Exception as exc:
        cost = (time.time() - start) * 1000
        logger.exception("Unhandled %s %s (%.2f ms): %s", request.method, request.url.path, cost, exc)
        return JSONResponse({"detail": "Internal Server Error"}, status_code=500)


@app.get("/")
def read_root():
    logger.debug("root endpoint visited")
    logger.info("root endpoint visited")
    logger.warning("root endpoint visited")
    logger.error("root endpoint visited")
    logger.critical("root endpoint visited")
    return {"Hello": "World"}


if __name__ == "__main__":
    app_cfg = setting_config.app
    uvicorn.run(
        app,
        host=app_cfg.host,
        port=app_cfg.port,
        reload=getattr(app_cfg, "debug", False),
        log_config=LOGGING_CONFIG,  # 统一 uvicorn & 业务日志
        log_level="debug",
    )
